package sublinear.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class SimpleLogger {
	
	public final static class LogFormatter extends Formatter {

	    private static final String LINE_SEPARATOR = System.getProperty("line.separator");
	    private static final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

	    @Override
	    public String format(LogRecord record) {
	        StringBuilder sb = new StringBuilder();

	        sb.append(dateFormat.format(new Date(record.getMillis())))
	            .append(" ")
	            .append(record.getLevel().getLocalizedName())
	            .append(": ")
	            .append(formatMessage(record))
	            .append(LINE_SEPARATOR);

	        if (record.getThrown() != null) {
	            try {
	                StringWriter sw = new StringWriter();
	                PrintWriter pw = new PrintWriter(sw);
	                record.getThrown().printStackTrace(pw);
	                pw.close();
	                sb.append(sw.toString());
	            } catch (Exception ex) {
	                // ignore
	            }
	        }

	        return sb.toString();
	    }
	}
	
	public static void initializeLogging(Level logLevel) {
		initializeLogging(logLevel, "AppLog.log");
	}
	
	public static void initializeLogging(Level logLevel, String logfile) {
		
		FileHandler fh;  
		Logger logger = Logger.getLogger("");

		logger.setLevel(logLevel);

		try {  
  
			fh = new FileHandler(logfile, true);  
			fh.setFormatter(new LogFormatter());  
			logger.addHandler(fh);
  
			logger.info("Debug output set");
			
		} catch (SecurityException e) {  
	        e.printStackTrace();  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    }
	}
	
	public static void setLogLevel(Level logLevel) {
		Logger logger = Logger.getLogger("");

		logger.setLevel(logLevel);		
	}

}
